package com.lczyfz.istep.common.utils.domain;

import java.util.List;

/**
 * Created by chenqk on 2017/4/26.
 */
public class NginxVhost {

    /**
     * 根域名
     */
    private String rootDomain;
    /**
     * 虚拟主机二级域名
     */
    private String subDomain;
    /**
     * 监听端口
     */
    private Integer listenPort = 80;
    /**
     * 访问日志路径
     */
    private String accessLogPath;
    /**
     * 错误日志路径
     */
    private String errorLogPath;
    /**
     * Nginx Reverse Proxy, format: ip:port
     */
    private List<UpstreamServer> upstreamServers;

    public String getRootDomain() {
        return rootDomain;
    }

    public void setRootDomain(String rootDomain) {
        this.rootDomain = rootDomain;
    }

    public String getSubDomain() {
        return subDomain;
    }

    public void setSubDomain(String subDomain) {
        this.subDomain = subDomain;
    }

    public Integer getListenPort() {
        return listenPort;
    }

    public void setListenPort(Integer listenPort) {
        this.listenPort = listenPort;
    }

    public String getAccessLogPath() {
        return accessLogPath;
    }

    public void setAccessLogPath(String accessLogPath) {
        this.accessLogPath = accessLogPath;
    }

    public String getErrorLogPath() {
        return errorLogPath;
    }

    public void setErrorLogPath(String errorLogPath) {
        this.errorLogPath = errorLogPath;
    }

    public List<UpstreamServer> getUpstreamServers() {
        return upstreamServers;
    }

    public void setUpstreamServers(List<UpstreamServer> upstreamServers) {
        this.upstreamServers = upstreamServers;
    }

    public String getPlainConfig() {
        StringBuffer buf = new StringBuffer();
        String virtualDomain = "virtual_" + subDomain;
        buf.append("upstream ").append(virtualDomain).append(" {\n");
        for (UpstreamServer server : upstreamServers) {
            buf.append("  server ").append(server.getPlainConfig()).append("\n");
        }
        buf.append("}\n");
        buf.append("server {\n");
        buf.append("  listen ").append(getListenPort()).append(";\n");
        buf.append("  server_name ").append(subDomain).append(".").append(rootDomain).append(";\n");
        buf.append("  location / {\n");
        buf.append("    proxy_pass http://").append(virtualDomain).append(";\n");
        buf.append("  }\n");
        if (accessLogPath != null) {
            buf.append("  access_log ").append(accessLogPath).append(";\n");
        }
        if (errorLogPath != null) {
            buf.append("  error_log  ").append(errorLogPath).append(";\n");
        }
        buf.append("}\n");
        return buf.toString();
    }
}
